package cn.xing.managementSystem.controller;

import cn.xing.managementSystem.bean.ResponseContent;
import cn.xing.managementSystem.commons.Constants;
import cn.xing.managementSystem.domain.SysUser;
import cn.xing.managementSystem.service.SysUserService;
import cn.xing.managementSystem.utils.Preconditions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * @author cuixing
 * @package cn.xing.managementSystem.controller
 * @class LoginController
 * @email xing.cui@magicwindow.cn
 * @date 2018/4/21 上午11:07
 * @description
 */
@Controller
public class LoginController {

    @Value("${credentialsSalt}")
    private String credentialsSalt;

    @Autowired
    private SysUserService sysUserService;

    @RequestMapping("/login")
    public String login() {

        return "login/login";
    }

    @RequestMapping("/toLogin")
    @ResponseBody
    public ResponseContent login(@RequestParam("username") String username,
                                 @RequestParam("password") String password, HttpServletRequest request) throws UnsupportedEncodingException {
        if(Preconditions.isNotBlank(username)){
            SysUser sysUser = sysUserService.getSysUserByUsername(username);
            if(Preconditions.isNotBlank(sysUser)){
                String encryptStrPassword = DigestUtils.md5Hex(password + credentialsSalt);
                if(sysUser.getPassword().equals(encryptStrPassword)){
                    request.getSession().setAttribute(Constants.GLOBAL_USER_KEY, sysUser);
                    request.getSession().setAttribute("user_name", username);
                    return ResponseContent.buildSuccess("login success!");
                }
            }
        }
        return ResponseContent.buildFail("username or password error");
    }



    @RequestMapping("/logout")
    @ResponseBody
    public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Object sysUser = request.getSession().getAttribute(Constants.GLOBAL_USER_KEY);
        if(Preconditions.isNotBlank(sysUser)){
            request.getSession().invalidate();
        }
        response.sendRedirect("/management_system/login");
    }

}